import type { User, LoginForm, RegisterForm, LoginResponse, RegisterResponse } from '@/types/auth'

// 模拟用户数据
const mockUsers: User[] = [
  {
    id: '1',
    username: 'admin',
    email: 'admin@example.com',
    avatar: 'https://cube.elemecdn.com/0/88/03b0d39583f48206768a7534e55bcpng.png',
    role: 'admin',
    createdAt: '2024-01-01T00:00:00Z',
    lastLoginAt: '2024-01-15T10:30:00Z'
  },
  {
    id: '2',
    username: 'user',
    email: 'user@example.com',
    avatar: 'https://cube.elemecdn.com/0/88/03b0d39583f48206768a7534e55bcpng.png',
    role: 'user',
    createdAt: '2024-01-02T00:00:00Z',
    lastLoginAt: '2024-01-14T15:20:00Z'
  }
]

// 模拟API延迟
const delay = (ms: number) => new Promise(resolve => setTimeout(resolve, ms))

export const authApi = {
  // 登录
  async login(loginForm: LoginForm): Promise<LoginResponse> {
    await delay(1000)
    
    const user = mockUsers.find(u => 
      u.username === loginForm.username || u.email === loginForm.username
    )
    
    if (!user) {
      throw new Error('用户不存在')
    }
    
    // 简单的密码验证（实际项目中应该使用加密）
    if (loginForm.password !== 'password') {
      throw new Error('密码错误')
    }
    
    // 更新最后登录时间
    user.lastLoginAt = new Date().toISOString()
    
    return {
      token: `mock-token-${user.id}-${Date.now()}`,
      user,
      expiresIn: 7200 // 2小时
    }
  },

  // 注册
  async register(registerForm: RegisterForm): Promise<RegisterResponse> {
    await delay(1000)
    
    // 检查用户名是否已存在
    const existingUser = mockUsers.find(u => 
      u.username === registerForm.username || u.email === registerForm.email
    )
    
    if (existingUser) {
      throw new Error('用户名或邮箱已存在')
    }
    
    // 验证密码确认
    if (registerForm.password !== registerForm.confirmPassword) {
      throw new Error('两次输入的密码不一致')
    }
    
    const newUser: User = {
      id: Date.now().toString(),
      username: registerForm.username,
      email: registerForm.email,
      role: 'user',
      createdAt: new Date().toISOString()
    }
    
    mockUsers.push(newUser)
    
    return {
      message: '注册成功',
      user: {
        username: newUser.username,
        email: newUser.email,
        role: newUser.role
      }
    }
  },

  // 登出
  async logout(): Promise<void> {
    await delay(500)
    // 在实际项目中，这里会调用后端API使token失效
  },

  // 获取用户信息
  async getUserInfo(): Promise<User> {
    await delay(300)
    
    // 从token中解析用户ID（这里简化处理）
    const token = localStorage.getItem('token')
    if (!token) {
      throw new Error('未登录')
    }
    
    const userId = token.split('-')[2] // 从mock token中提取用户ID
    const user = mockUsers.find(u => u.id === userId)
    
    if (!user) {
      throw new Error('用户不存在')
    }
    
    return user
  },

  // 修改密码
  async changePassword(oldPassword: string, newPassword: string): Promise<void> {
    await delay(800)
    
    // 验证旧密码
    if (oldPassword !== 'password') {
      throw new Error('原密码错误')
    }
    
    // 在实际项目中，这里会更新数据库中的密码
    console.log('密码已更新')
  },

  // 更新用户信息
  async updateProfile(updates: Partial<Pick<User, 'username' | 'email' | 'avatar'>>): Promise<User> {
    await delay(600)
    
    const token = localStorage.getItem('token')
    if (!token) {
      throw new Error('未登录')
    }
    
    const userId = token.split('-')[2]
    const userIndex = mockUsers.findIndex(u => u.id === userId)
    
    if (userIndex === -1) {
      throw new Error('用户不存在')
    }
    
    // 更新用户信息
    mockUsers[userIndex] = { ...mockUsers[userIndex], ...updates }
    
    return mockUsers[userIndex]
  }
} 